import { makeAutoObservable } from 'mobx';
import { FlowPath, FlowPathFormValues } from './flowpathTypes';
import { getFlowPathList, createFlowPath, updateFlowPath, deleteFlowPath } from '../../../../apis/backhub/flowpath';

class FlowPathStore {
  flowPaths: FlowPath[] = [];
  modalVisible = false;
  editingFlowPath: FlowPath | undefined = undefined;
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取工作流列表
  fetchFlowPaths = async () => {
    this.loading = true;
    try {
      this.flowPaths = await getFlowPathList();
    } catch (error) {
      console.error('获取工作流列表失败:', error);
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingFlowPath = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (flowPath: FlowPath) => {
    this.editingFlowPath = flowPath;
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingFlowPath = undefined;
  };

  // 保存工作流
  saveFlowPath = async (values: FlowPathFormValues) => {
    try {
      if (this.editingFlowPath && this.editingFlowPath.id) {
        await updateFlowPath(this.editingFlowPath.id, values);
      } else {
        await createFlowPath(values);
      }
      this.hideModal();
      this.fetchFlowPaths();
    } catch (error) {
      console.error('保存工作流失败:', error);
    }
  };

  // 删除工作流
  deleteFlowPath = async (id: string) => {
    try {
      await deleteFlowPath(id);
      this.fetchFlowPaths();
    } catch (error) {
      console.error('删除工作流失败:', error);
    }
  };
}

export const flowPathStore = new FlowPathStore();